// index.js
var app = getApp();

Page({

  data: {
    showDevices: false,
    selectedDevice: {},
    totalDevices: {},
  },

  onLoad(options) {
    //检测是否登录
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/login/login',
      });
    }
    else {
      this.setData({ baseUrl: app.globalData.baseUrl });

      var page = this;
      //console.log(app.globalData.userInfo);
      //获取设备信息
      wx.request({
        url: app.globalData.baseUrl + '/api/services/app/Device/GetAll',
        data: {
          UserId: app.globalData.userInfo.id,
          SkipCount: 0,
          MaxResultCount: 999
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if (res.data.success) {
            if (res.data.result.items.length > 0) {
              //绑定设备信息
              var selectedItem = res.data.result.items[0];
              var totalItems = [];
              res.data.result.items.forEach(entity => {
                totalItems.push(entity);
              });
              page.setData({
                selectedDevice: selectedItem,
                totalDevices: totalItems,
                deviceType: selectedItem.deviceTypeId == 15 ? '视觉数蛋器' : '激光数蛋器'
              });
              //绑定全局变量
              app.globalData.selectedDevice = selectedItem;
              app.globalData.totalDevices = totalItems;
            }
          }
          else {
            console.log(res);
          }
        }
      })
    }
  },

  showRealTime(event) {
    wx.navigateTo({
      url: '/pages/realtime/realtime',
    })
  },
  showHitory(event) {
    wx.navigateTo({
      url: '/pages/history/history',
    })
  },
  showChart(event) {
    wx.navigateTo({
      url: '/pages/chart/chart',
    })
  },
  showAnalysis(event) {
    wx.navigateTo({
      url: '/pages/analysis/analysis',
    })
  },
  showDeviceList() {
    this.setData({ showDevices: true });
  },
  closeDeviceList() {
    this.setData({ showDevices: false });
  },
  changeSelectedDevice(e) {
    var selected = e.currentTarget.dataset["item"];
    this.setData({
      selectedDevice: selected,
      showDevices: false,
      deviceType: selected.deviceTypeId == 15 ? '视觉数蛋器' : '激光数蛋器'
    });
    //更新全局变量
    app.globalData.selectedDevice = selected;
    //app.globalData.totalDevices = totalItems;
  },
  userLogout() {
    wx.removeStorageSync('autologin');
    wx.removeStorageSync('remember');
    wx.removeStorageSync('username');
    wx.removeStorageSync('password');
    app.globalData.userInfo = null;
    app.globalData.token = '';

    wx.navigateTo({
      url: '/pages/login/login',
    });
  }
})
